package cn.keduox.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.keduox.entity.Book;
import cn.keduox.entity.CartDetail;
import cn.keduox.entity.CartList;
import cn.keduox.service.CartService;


/**
 * 购物车控制层
 * 
 * @author 邓中亚
 *
 */
@WebServlet("/cart.do")
public class CartController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 设置编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String servletFlag = req.getParameter("servletFlag");
		if ("addCartDetail".equals(servletFlag)) {
			addCart(req, resp);
		} else if ("showCart".equals(servletFlag)) {
			showCart(req, resp);
		}

	}
/**
 * 将书籍添加进购物车
 * @param req
 * @param resp
 * @throws ServletException
 * @throws IOException
 */
	private void addCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("添加购物车详情表");
		//获取书籍id和购物车详情id
		String bookId = req.getParameter("bookId");
		String cartId = req.getParameter("cartId");
		CartService cartService = new CartService();
		// Result result=new Result();
		// System.out.println(result.isState());
		Book book = new Book();
		book = cartService.addCart(bookId, cartId);
		System.out.println(book.getName());
		System.out.println(book.getMarketPrice());
		System.out.println(book.getCoverUrl());
		//跳转至书籍成功添加至购物车页面
		req.setAttribute("book", book);
		req.setAttribute("cartId", cartId);
		req.getRequestDispatcher("/WEB-INF/pages/cartAddSuccess.jsp").forward(req, resp);
	}
/**
 * 显示该用户购物车中所有书籍
 * @param req
 * @param resp
 * @throws IOException 
 * @throws ServletException 
 */
	private void showCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("显示购物车列表");
		//获取用户id
		String cartId = req.getParameter("cartId");
		System.out.println(cartId);
		//将数据传给服务层去查找书籍
		CartService cartService = new CartService();
		List<CartList> cartListList=cartService.showCart(cartId);
		int sum=0;int size=cartListList.size();//获取总价和书籍数量
		for (int i = 0; i < cartListList.size(); i++) {
			sum=sum+cartListList.get(i).getSubPrice();
		}
		req.setAttribute("size", size);
		req.setAttribute("sum", sum);
		req.setAttribute("cartListList", cartListList);
		req.getRequestDispatcher("/WEB-INF/pages/showCart.jsp").forward(req, resp);//cartList   showCart
		
	}

}
